package com.tsd.core.utils;

import com.tsd.core.constants.Constants;
import com.tsd.core.vo.HlpException;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName: RequestUtils
 * @Description: HttpServletRequest工具类
 * @Author: Hillpool
 * @Date: 2022/7/15 10:14
 * @Version: 1.0
 */
public class RequestUtils {


    /**
     * 获取请求的参数
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws HlpException
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getReqParams(HttpServletRequest request) throws Exception {
        Map<String, Object> result = (Map<String, Object>) request.getAttribute(Constants.REQ_ATTRIBUTE_NAME_PARAMS);
        if (result != null) {
            return result;
        }
        return getParams(request);
    }

    /**
     * 获取请求的参数
     * 支持form方式、raw json方式
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws HlpException
     */
    public static Map<String, Object> getParams(HttpServletRequest request) throws UnsupportedEncodingException, HlpException {
        Map<String, Object> result = new HashMap<String, Object>();
        String contentType = request.getContentType();
        boolean flag = contentType != null && contentType.contains("form");
        if (flag || RequestMethod.GET.name().equals(request.getMethod())) {
            //form-data方式,就算有文件也不处理
            //x-www-form-urlencoded 也会到这里，通过request.getParameterMap会进行decode
            Map<String, String[]> map = request.getParameterMap();
            Set<String> keys = map.keySet();
            for (String key : keys) {
                String[] obj = map.get(key);
                result.put(key, obj.length == 0 ? null : (obj.length == 1 ? obj[0] : obj));
            }
        } else {
            String json = getInputStreamString(request);
            if (json.startsWith("{")) {
                //JSON格式,
                result = JsonUtil.parseObject(json);
            } else {
                //x-www-form-urlencoded方式，在swagger UI发出的form-data指令是这样的
                json = URLDecoder.decode(json, "UTF-8");
                String[] params = json.split("&");
                for (String p : params) {
                    String[] ps = p.split("=");
                    result.put(ps[0], ps.length == 1 ? null : ps[1]);
                }
            }
        }
        return result;
    }

    public static String getInputStreamString(HttpServletRequest request) {
        StringBuilder body = new StringBuilder();
        int counter = 0;
        InputStream stream;
        try {
            stream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                if (counter > 0) {
                    body.append("\r\n");
                }
                body.append(line);
                if (counter == 0) {
                    counter++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body.toString();
    }

    /**
     * 输出内容到http响应
     *
     * @param response
     * @param result
     * @throws IOException
     */
    public static void writeResponse(HttpServletResponse response, Object result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/json;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.append(JackJsonUtils.encode(result));
    }
}
